<template>
  <view class="content padd20">
    <view class="zjsc">
      <!-- <image class="cover-img" :src="imagesIcon[0]" mode="aspectFill"></image> -->
      行驶证(必填)
    </view>
    <view class="box-content padtb30">
      <view class="ghmsc">
        <view class="sctp" @click="selectIdFace">
          <view class="img-box">
            <image class="cover-img" :src="imagesPathFace[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{
              showBackWord1 ? '重新上传' : '点击上传行驶证正本'
              }}</view>
          </view>
        </view>
        <view class="sctp" @click="selectCardBack">
          <view class="img-box">
            <image class="cover-img" :src="imagesPathBack[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{
              showBackWord2 ? '重新上传' : '点击上传行驶证副本'
              }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="box-content">
      <view class="qrsf">
        <view class="sjxx">
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>车牌号</view>
            <input class="uni-input" v-model="vehicleInfo.vehicleNo" @blur="handleVehicleNo()" :disabled="!editable" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>车辆类型</view>
            <view class="uni-select-box">
              <view class="uni-input" @click="showPopVehicle">{{
                vehicleTypeName
                }}</view>
              <uni-icons type="forward" size="20"></uni-icons>
              <uv-picker ref="selectVehiclePop" :confirmColor="curColor" :columns="vehicleData" keyName="label"
                @confirm="confirmChange"></uv-picker>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>所有人</view>
            <input class="uni-input" v-model="vehicleInfo.possessor" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>发证机关</view>
            <input class="uni-input" v-model="vehicleInfo.issuingAuthority" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>能源类型</view>
            <view class="uni-select-box">
              <view class="uni-input" @click="showPopEnergy">{{
                energyTypeName
                }}</view>
              <uni-icons type="forward" size="20"></uni-icons>
              <uv-picker ref="selectEnergyPop" :confirmColor="curColor" :columns="energyData" keyName="label"
                @confirm="confirmEnergyType"></uv-picker>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>车牌颜色:</view>
            <view class="uni-select-box">
              <view class="uni-input" @click="showPop">{{
                licensePlateColorName
                }}</view>
              <uni-icons type="forward" size="20"></uni-icons>
              <uv-picker ref="selectBoxPop" :confirmColor="curColor" :columns="licensePlateColorData" keyName="label"
                @confirm="confirmPop"></uv-picker>
            </view>
          </view>
          <view class="uni-form-item no-border">
            <view class="title"><span v-if="['Q11','Q12'].includes(vehicleInfo.vehicleType)"
                style="color: red">*</span>挂车车牌号</view>
            <input class="uni-input" v-model="vehicleInfo.trailerVehicleNo" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>注册日期</view>
            <w-picker :visible="registrationDateShow" mode="date" startYear="1900" endYear="2124"
              :value="vehicleInfo.registrationDate" :current="false" fields="day"
              @confirm="registrationDateConfirm($event)" @cancel="registrationDateCancel"
              :disabled-after="false"></w-picker>
            <input class="uni-input" v-model="vehicleInfo.registrationDate" placeholder="注册日期" disabled="true"
              @click="registrationDateShow=true"></input>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>发证日期</view>
            <w-picker :visible="issueDateShow" mode="date" startYear="1900" endYear="2124"
              :value="vehicleInfo.issueDate" :current="false" fields="day" @confirm="issueDateConfirm($event)"
              @cancel="issueDateCancel" :disabled-after="false"></w-picker>
            <input class="uni-input" v-model="vehicleInfo.issueDate" placeholder="注册日期" disabled="true"
              @click="issueDateShow=true"></input>
          </view>
        </view>
      </view>
    </view>
    <view class="zjsc"> 道路运输证信息(必填) </view>
    <view class="box-content padtb30">
      <view class="ghmsc">
        <view class="sctp" @click="selectRoadFace">
          <view class="img-box">
            <image class="cover-img" :src="imagesPathRoad[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{
              showBackWord3 ? '重新上传' : '点击上传道路运输证'
              }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="box-content" style="margin-bottom: 147rpx">
      <view class="qrsf">
        <view class="sjxx">
          <view class="uni-form-item">
            <view class="title w232"><span style="color: red">*</span>道路运输证号</view>
            <input class="uni-input" v-model="vehicleInfo.transportPermitNo" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title w232"><span style="color: red">*</span>业户名称</view>
            <input class="uni-input" v-model="vehicleInfo.proprietorName" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title w232"><span style="color: red">*</span>经营许可证号</view>
            <input class="uni-input" v-model="vehicleInfo.bizLicenseNumber" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title">注册日期</view>
            <w-picker :visible="registerDateShow" mode="date" startYear="1900" endYear="2124"
              :value="vehicleInfo.roadTransportCertificateRegistrationDate" :current="false" fields="day"
              @confirm="registerDateConfirm($event)" @cancel="registerDateCancel" :disabled-after="false"></w-picker>
            <input class="uni-input" v-model="vehicleInfo.roadTransportCertificateRegistrationDate" placeholder="注册日期"
              disabled="true" @click="registerDateShow=true"></input>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>有效期至</view>
            <w-picker :visible="validUntilShow" mode="date" startYear="1900" endYear="2124"
              :value="vehicleInfo.roadTransportCertificateEndDate" :current="false" fields="day"
              @confirm="validUntilConfirm($event)" @cancel="validUntilCancel" :disabled-after="false"></w-picker>
            <input class="uni-input" v-model="vehicleInfo.roadTransportCertificateEndDate" placeholder="有效期至"
              disabled="true" @click="validUntilShow=true"></input>
          </view>
          <view class="uni-form-item no-border">
            <view class="title">审核日期</view>
            <w-picker :visible="auditDateShow" mode="date" startYear="1900" endYear="2124"
              :value="vehicleInfo.roadTransportCertificateExamineDate" :current="false" fields="day"
              @confirm="auditDateConfirm($event)" @cancel="auditDateCancel" :disabled-after="false"></w-picker>
            <input class="uni-input" v-model="vehicleInfo.roadTransportCertificateExamineDate" placeholder="审核日期"
              disabled="true" @click="auditDateShow=true"></input>
          </view>
        </view>
      </view>
    </view>

    <view class="btns" v-if="mtype == 'update'">
      <button :class="{ loading: isLoading }" type="primary" @click="handleSubmit">
        保存
        <view v-if="isLoading" class="loading-icon"></view>
      </button>
    </view>
    <view v-else class="btns">
      <button :class="{ loading: isLoading }" type="primary" @click="handleSubmit">
        提交
        <view v-if="isLoading" class="loading-icon"></view>
      </button>
    </view>
  </view>
</template>
<script>
  import {
    getVehicleRecognize,
    getVehicleOneDetail,
    updateVehicle,
    addVehicle,
    getDictDatas
  } from '@/api/me.js';
  import { getAccessToken } from '@/utils/auth';
  import config from '@/config';
  import { toast } from '@/utils/common';
  import { dictTansParams, timestampToChineseDate } from '@/utils/common.js';

  export default {
    data() {
      return {
        vehicleData: [],
        isLoading: false,
        vehicleTypeName: '',
        energyTypeName: '',
        licensePlateColorName: '',
        showBackWord1: false,
        showBackWord2: false,
        showBackWord3: false,
        vehicleType: null,
        energyType: null,
        licensePlateColor: null,
        energyData: [],
        licensePlateColorData: [],
        imagesIcon: [],
        imageStyles: {
          width: 180,
          height: 110
        },
        uploadImgMess1: false, //行驶证正面
        uploadImgMess2: false, //行驶证背面
        uploadImgMess3: false, //道路证
        imagesPathFace: [config.baseImgUrl + '/driver-licenseFace.png'],
        imagesPathBack: [config.baseImgUrl + '/driver-licenseBack.png'],
        imagesPathRoad: [config.baseImgUrl + '/road-transport.png'],
        mtype: '',
        validateno: false,
        registrationDateShow: false,
        issueDateShow: false,
        registerDateShow: false,
        validUntilShow: false,
        auditDateShow: false,
        vehicleInfo: {
          vehicleFaceUrl: '',
          vehicleBackUrl: '',
          vehicleNo: '',
          vehicleType: '',
          possessor: '',
          issuingAuthority: '',
          energyType: '',
          licensePlateColor: '',
          trailerVehicleNo: '',
          transportPermitUrl: '',
          transportPermitNo: '',
          proprietorName: '',
          bizLicenseNumber: '',
          carLength: '9600mm',
          isIdentified: '',
          isTransportPermitIdentified: '',
          brand: '',
          vin: '',
          registrationDate: undefined,
          issueDate: undefined,
          totalQuality: '',
          ratedLoad: '',
          unladenMass: '',
          functions: '',
          tractionMass: '',
          vehicleLicenseFrontPic: undefined, //网货（卡漠）行驶证正面图片
          vehicleLicenseReversePic: undefined, //网货（卡漠）行驶证背面图片
          operationLicensePic: undefined, //网货（卡漠）道路运输证图片
          roadTransportCertificateRegistrationDate: '',
          roadTransportCertificateEndDate: '',
          roadTransportCertificateExamineDate: '',
          sync: false,
        },
        faceUpload: false,
        backUpload: false,
        TransportUpload: false,
        type: '',
        rangeTime: '',
        errorMsg: '',
        dataSource: undefined,
        editable: true
      };
    },
    onLoad(options) {
      //获取字典
      this.getLicenseTypeDict();
      if (options.id) {
        this.getVehivleDict(options.id);
        return
      }
      if (options.type) {
        this.type = options.type;
        return
      }
    },
    computed: {
      curColor() {
        return this.$store.state.user.curTypeColor;
      },
      imagesCamera() {
        if (this.$store.state.user.curTypeColor == '#D22C2C') {
          return config.baseImgUrl + '/camera1.png';
        } else if (this.$store.state.user.curTypeColor == '#409EFE') {
          return config.baseImgUrl + '/camera.png';
        } else {
        }
      }
    },
    methods: {
      showPop() {
        this.$refs['selectBoxPop'].open('bottom');
      },
      showPopEnergy() {
        this.$refs['selectEnergyPop'].open('bottom');
      },
      showPopVehicle() {
        this.$refs['selectVehiclePop'].open('bottom');
      },
      confirmPop(e) {
        if (this.licensePlateColorData.length > 0) {
          this.licensePlateColorName = e.value[0].label;
          this.vehicleInfo.licensePlateColor = e.value[0].value;
        }
      },
      confirmChange(e) {
        if (this.vehicleData.length > 0) {
          this.vehicleTypeName = e.value[0].label;
          this.vehicleInfo.vehicleType = e.value[0].value;
        }
      },
      confirmEnergyType(e) {
        if (this.energyData.length > 0) {
          this.energyTypeName = e.value[0].label;
          this.vehicleInfo.energyType = e.value[0].value;
        }
      },
      async getLicenseTypeDict() {
        let datas = await getDictDatas();
        if (!!datas)
          this.vehicleData = [
            datas.data.filter((e) => e.dictType === 'vehicle_type')
          ];
        if (!!datas)
          this.energyData = [
            datas.data.filter((e) => e.dictType === 'energy_type')
          ];
        if (!!datas)
          this.licensePlateColorData = [
            datas.data.filter((e) => e.dictType === 'license_plate_color')
          ];
      },
      changeAccount(res) {
        console.log(res);
      },
      registrationDateConfirm(res) {
        this.vehicleInfo.registrationDate = res.result
        this.registrationDateShow = false
      },
      registrationDateCancel() {
        this.registrationDateShow = false
      },
      issueDateConfirm(res) {
        this.vehicleInfo.issueDate = res.result
        this.issueDateShow = false
      },
      issueDateCancel(res) {
        this.issueDateShow = false
      },
      registerDateConfirm(res) {
        this.vehicleInfo.roadTransportCertificateRegistrationDate = res.result
        this.registerDateShow = false
      },
      validUntilConfirm(res) {
        this.vehicleInfo.roadTransportCertificateEndDate = res.result
        this.validUntilShow = false
      },
      auditDateConfirm(res) {
        this.vehicleInfo.roadTransportCertificateExamineDate = res.result
        this.auditDateShow = false
      },
      registerDateCancel() {
        this.registerDateShow = false
      },
      validUntilCancel() {
        this.validUntilShow = false
      },
      auditDateCancel() {
        this.auditDateShow = false
      },
      //获取单个车辆认证信息
      async getVehivleDict(id) {
        try {
          let res = await getVehicleOneDetail(id);
          if (res.code == 0) {
            const result = res.data;
            this.vehicleInfo = result;
            this.vehicleInfo.roadTransportCertificateRegistrationDate = result?.roadTransportCertificateRegistrationDate ? result?.roadTransportCertificateRegistrationDate : ''
            this.vehicleInfo.roadTransportCertificateEndDate = result?.roadTransportCertificateEndDate ? result?.roadTransportCertificateEndDate : ''
            this.vehicleInfo.roadTransportCertificateExamineDate = result?.roadTransportCertificateExamineDate ? result?.roadTransportCertificateExamineDate : ''
            //获取字典
            let datas = await getDictDatas();
            if (!!datas)
              this.vehicleData = [
                datas.data.filter((e) => e.dictType === 'vehicle_type')
              ];
            for (let item of this.vehicleData[0]) {
              if (this.vehicleInfo.vehicleType == item.value) {
                this.vehicleTypeName = item.label;
                break;
              } else {
                this.vehicleTypeName = '';
              }
            }
            if (!!datas)
              this.energyData = [
                datas.data.filter((e) => e.dictType === 'energy_type')
              ];
            for (let item of this.energyData[0]) {
              if (this.vehicleInfo.energyType == item.value) {
                this.energyTypeName = item.label;
                break;
              } else {
                this.energyTypeName = '';
              }
            }
            if (!!datas)
              this.licensePlateColorData = [
                datas.data.filter((e) => e.dictType === 'license_plate_color')
              ];
            for (let item of this.licensePlateColorData[0]) {
              if (this.vehicleInfo.licensePlateColor.toString() == item.value) {
                this.licensePlateColorName = item.label;
                break;
              } else {
                this.licensePlateColorName = '';
              }
            }
            this.mtype = 'update';
            if (!!res.data.vehicleFaceUrl) {
              this.showBackWord1 = true;
              this.imagesPathFace = [];
              this.imagesPathFace.push(res.data.vehicleFaceUrl);
              this.faceUpload = true;
            }
            if (!!res.data.vehicleBackUrl) {
              this.showBackWord2 = true;
              this.imagesPathBack = [];
              this.imagesPathBack.push(res.data.vehicleBackUrl);
              this.backUpload = true;
            }
            if (!!res.data.transportPermitUrl) {
              this.showBackWord3 = true;
              this.imagesPathRoad = [];
              this.imagesPathRoad.push(res.data.transportPermitUrl);
              this.TransportUpload = true;
            }
            if (res.data.energyType == null) {
              res.data.energyType = 'D';
            }
            if (res.data.licensePlateColor == null) {
              res.data.licensePlateColor = 1;
            }
            if (res.data.vehicleNo != null) {
              this.editable = false;
            }
          }
        } catch (e) {
          return false;
        }
      },

      // 提交车辆信息
      async handleSubmit() {
        if (this.isLoading) return;
        //校验参数
        if (this.validParams()) {
          return
        }
        const data = this.vehicleInfo;
        data['trailerLicensePlateColor'] = this.vehicleInfo.licensePlateColor
        if (this.faceUpload == true && this.backUpload == true) {
          data.isIdentified = true;
        } else {
          data.isIdentified = false;
        }
        if (this.TransportUpload == true) {
          data.isTransportPermitIdentified = true;
        } else {
          data.isTransportPermitIdentified = false;
        }
        try {
          this.isLoading = true;
          if (this.mtype == 'update') {
            data.sync = true
            let res = await updateVehicle(data);
            if (res.code == 0) {
              uni.showToast({
                title: `更新成功`
              });
            } else {
              toast(res.msg);
              this.isLoading = false
              return;
            }
          } else {
            let res = await addVehicle(data);
            if (res.code == 0) {
              uni.showToast({
                title: `添加成功`
              });
            } else {
              toast(res.msg);
              this.isLoading = false
              return;
            }
          }
          if (this.type === 'code') {
            //上一步是扫码接单
            if (uni.getStorageSync('isSetSjxx') === 'net') {
              this.$tab.reLaunch('/pages/receivingNet?codes=true');
            } else if (uni.getStorageSync('isSetSjxx') === 'bj') {
              this.$tab.reLaunch('/pages/receivingBJ?codes=true');
            } else if (uni.getStorageSync('isSetSjxx') === 'jy') {
              this.$tab.reLaunch('/pages/receivingJY?codes=true');
            } else if (uni.getStorageSync('isSetSjxx') === 'jl') {
              this.$tab.reLaunch('/pages/receiving?codes=true');
            }
          } else {
            this.$tab.reLaunch('/packageB/pages/mine/vehicle/vehicle');
          }
        } finally {
          this.isLoading = false;
        }
      },
      validParams() {
        if (this.uploadImgMess1) {
          toast(`请上传合适的行驶证正面`);
          return true;
        }
        if (!this.vehicleInfo.vehicleBackUrl) {
          toast(`请上传行驶证反面`);
          return true;
        }
        if (this.uploadImgMess2) {
          toast(`请上传合适的行驶证反面`);
          return true;
        }
        if (!this.vehicleInfo.vehicleBackUrl) {
          toast(`请上传行驶证反面`);
          return true;
        }

        if (!this.vehicleInfo.vehicleNo) {
          toast(`请输入车牌号`);
          return true;
        }
        const inputLength = this.vehicleInfo.vehicleNo.length;
        if (inputLength < 7 || inputLength > 8) {
          toast(`车牌号长度7到8位`);
          return true;
        }
        if (!this.vehicleInfo.vehicleType) {
          toast(`请选择车辆类型`);
          return true;
        }
        if (!this.vehicleInfo.possessor) {
          toast(`请输入所有人`);
          return true;
        }
        if (!this.vehicleInfo.issuingAuthority) {
          toast(`请输入发证机关`);
          return true;
        }
        if (!this.vehicleInfo.energyType) {
          toast(`请选择能源类型`);
          return true;
        }
        if (!this.vehicleInfo.licensePlateColor) {
          toast(`请选择车辆颜色`);
          return true;
        }
        if (['Q11', 'Q12'].includes(this.vehicleInfo.vehicleType)) {
          if (!this.vehicleInfo.trailerVehicleNo) {
            toast(`请选择挂车车牌号`);
            return true;
          }
          const inputLength1 = this.vehicleInfo.trailerVehicleNo.length;
          if (inputLength1 > 0) {
            if (inputLength1 < 7 || inputLength1 > 8) {
              toast(`挂车车牌号长度7到8位`);
              return true;
            }
          }
        }
        if (!this.vehicleInfo.registrationDate) {
          toast(`请选择行驶证注册日期`);
          return true;
        }
        const registrationDateYear = this.vehicleInfo.registrationDate?.split('-')?.[0]
        if (registrationDateYear?.length !== 4) {
          toast(`行驶证注册日期格式错误`);
          return true;
        }
        if (!this.vehicleInfo.issueDate) {
          toast(`请选择行驶证发证日期`);
          return true;
        }
        const issueDateYear = this.vehicleInfo.issueDate?.split('-')?.[0]
        if (issueDateYear?.length !== 4) {
          toast(`行驶证发证日期格式错误`);
          return true;
        }
        if (!this.vehicleInfo.transportPermitUrl) {
          toast(`道路运输证图片不能为空，请上传`);
          return true;
        }
        if (this.uploadImgMess3) {
          toast(`请上传合适的道路运输证图片`);
          return true;
        }
        if (!this.vehicleInfo.bizLicenseNumber) {
          toast(`经营许可证号不能为空`);
          return true;
        }

        if (!this.vehicleInfo.proprietorName) {
          toast(`业户名称不能为空`);
          return true;
        }
        if (!this.vehicleInfo.transportPermitNo) {
          toast(`道路运输证号不能为空`);
          return true;
        }
        if (!this.vehicleInfo.roadTransportCertificateEndDate) {
          toast(`请选择道路运输证有效期至`);
          return true;
        }
        return false
      },
      selectIdFace(e) {
        let that = this;
        //同时进行
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size;
            let quelityVal = 100;
            let initnum = 0.3 * 1024 * 1024;
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum);
            }
            that.imagesPathFace = [];
            that.imagesPathFace.push(res.tempFilePaths[0]);

            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                that.uploadFilesKamo(resp.tempFilePath, 1);
                that.uploadFilesId(resp.tempFilePath, 1);
              },
              fail: (error) => { }
            });
          },
          fail(e) {
            console.log('上传行驶证正面的照片fail：', e);
          }
        });
      },
      selectCardBack(e) {
        let that = this;
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size;
            let quelityVal = 100;
            let initnum = 0.3 * 1024 * 1024;
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum);
            }
            that.imagesPathBack = [];
            that.imagesPathBack.push(res.tempFilePaths[0]);

            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                console.log('res.tempFilePath???：', res.tempFilePath);
                that.uploadFilesKamo(resp.tempFilePath, 2);
                that.uploadFilesId(resp.tempFilePath, 2);
              },
              fail: (error) => { }
            });
          },
          fail(e) {
            console.log('上传行驶证反面的照片fail：', e);
          }
        });
      },
      selectRoadFace(e) {
        let that = this;
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size;
            let quelityVal = 100;
            let initnum = 0.3 * 1024 * 1024;
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum);
            }
            that.imagesPathRoad = [];
            that.imagesPathRoad.push(res.tempFilePaths[0]);

            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                that.uploadFilesKamo(resp.tempFilePath, 3);
                that.uploadFiles(resp.tempFilePath, 0, 'img');
              },
              fail: (error) => { }
            });
          },
          fail(e) {
            console.log('上传道路运输证的照片失败', e);
          }
        });
      },
      uploadFiles(filepath, type) {
        wx.showLoading({
          title: '正在上传中...'
        });
        let _ = this;
        uni.uploadFile({
          url: config.baseUrl + '/infra/file/upload',
          filePath: filepath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            Authorization: 'Bearer ' + getAccessToken()
          },
          async success(res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
              _.uploadImgMess3 = false;
              _.showBackWord3 = true;
              _.vehicleInfo.transportPermitUrl = JSON.parse(res.data).data;
              _.TransportUpload = true;
              let msg = '',
                iconFlag = '';
              msg = '上传成功';
              iconFlag = 'success';
              uni.showToast({
                title: msg,
                icon: 'success'
              });
            } else {
              _.uploadImgMess3 = true;
              if (res.statusCode === 413) {
                toast('上传图片过大，请重新上传，不要选择原图');
              } else {
                toast('上传失败，状态码:', res.statusCode);
              }
            }
          },
          fail(err) {
            uni.showToast({
              title: '上传失败'
            });
          }
        });
      },
      uploadFilesId(filepath, type) {
        wx.showLoading({
          title: '正在上传中...'
        });
        let _ = this;
        // _.faceUpload = false
        // _.backUpload = false
        uni.uploadFile({
          url: config.baseUrl + '/infra/file/upload',
          filePath: filepath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            Authorization: 'Bearer ' + getAccessToken()
          },
          async success(res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
              if (type == 1) {
                _.showBackWord1 = true;
                _.vehicleInfo.vehicleFaceUrl = JSON.parse(res.data).data;
              } else if (type == 2) {
                _.showBackWord2 = true;
                _.vehicleInfo.vehicleBackUrl = JSON.parse(res.data).data;
              }
              let res1 = await getVehicleRecognize(JSON.parse(res.data).data);
              let msg = '',
                iconFlag = '';
              if (res1.code == 0) {
                _.validateno = true;
                if (type == 1) {
                  _.uploadImgMess1 = false;
                  msg = '上传成功';
                  if (_.editable == true) {
                    _.vehicleInfo.vehicleNo =
                      (!!res1.data.face &&
                        res1.data.face.data.licenseplatenumber).toUpperCase().replace(/ /g, '') ||
                      '';
                  }
                  const vehicleTypeText = (!!res1.data.face && res1.data.face.data.vehicletype) || '';
                  const vehicleList = _.vehicleData.flat(Infinity)
                  for (const item of vehicleList) {
                    if (vehicleTypeText === item.label) {
                      _.vehicleInfo.vehicleType = item.value;
                      _.vehicleTypeName = item.label;
                      break;
                    } else {
                      _.vehicleInfo.vehicleType = 'H11';
                      _.vehicleTypeName = '重型普通货车';
                    }
                  }
                  _.vehicleInfo.possessor =
                    (!!res1.data.face && res1.data.face.data.owner) || '';
                  _.vehicleInfo.issuingAuthority =
                    (!!res1.data.face && res1.data.face.data.issueauthority) ||
                    '';
                  _.vehicleInfo.brand =
                    (!!res1.data.face && res1.data.face.data.model) || '';
                  _.vehicleInfo.vin =
                    (!!res1.data.face && res1.data.face.data.vincode) || '';
                  const registrationDateStr = (!!res1.data.face && res1.data.face.data.registrationdate) || '';
                  if (!isNaN(new Date(registrationDateStr))) {
                    _.vehicleInfo.registrationDate = timestampToChineseDate(registrationDateStr)
                  } else {
                    _.vehicleInfo.registrationDate = ''
                  }
                  const issueDateStr = (!!res1.data.face && res1.data.face.data.issuedate) || ''
                  if (!isNaN(new Date(issueDateStr))) {
                    _.vehicleInfo.issueDate = timestampToChineseDate(issueDateStr)
                  } else {
                    _.vehicleInfo.issueDate = ''
                  }
                  _.vehicleInfo.functions =
                    (!!res1.data.face && res1.data.face.data.usenature) || '';
                  _.faceUpload = true;
                } else if (type == 2) {
                  _.uploadImgMess2 = false;
                  msg = '上传成功';
                  _.vehicleInfo.totalQuality =
                    (!!res1.data.back && res1.data.back.data.totalweight) || '';
                  _.vehicleInfo.ratedLoad =
                    (!!res1.data.back && res1.data.back.data.permittedweight) ||
                    '';
                  _.vehicleInfo.unladenMass =
                    (!!res1.data.back && res1.data.back.data.curbweight) || '';
                  _.vehicleInfo.trailerVehicleNo =
                    (!!res1.data.back &&
                      res1.data.back.data.licenseplatenumber) ||
                    '';
                  _.vehicleInfo.tractionMass =
                    (!!res1.data.back && res1.data.back.data.tractionweight) ||
                    '';
                  _.backUpload = true;
                }
                iconFlag = 'success';
              } else {
                msg = res1.msg;
                iconFlag = 'none';
                _.errorMsg = res1.msg;
                _.validateno = false;
                //识别失败或上传失败，就清空图片
                if (type == 1) {
                  _.imagesPathFace = [];
                  _.vehicleInfo.vehicleFaceUrl = undefined;
                } else if (type == 2) {
                  _.imagesPathBack = [];
                  _.vehicleInfo.vehicleBackUrl = undefined;
                }
              }
              wx.hideLoading();
              toast(msg);
            } else {
              if (type == 1) _.uploadImgMess1 = true;
              else _.uploadImgMess2 = true;
              if (res.statusCode === 413) {
                toast('上传图片过大，请重新上传，不要选择原图');
              } else {
                toast('上传失败，状态码:', res.statusCode);
              }
            }
          },
          fail(err) {
            uni.showToast({
              title: '上传失败'
            });
          }
        });
      },
      uploadFilesKamo(filepath, type) {
        //上传卡漠
        let _ = this;
        uni.uploadFile({
          url: config.baseUrl + '/queue/freight-kamo/upload',
          filePath: filepath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            Authorization: 'Bearer ' + getAccessToken()
          },
          async success(res) {
            if (type == 1)
              _.vehicleInfo.vehicleLicenseFrontPic = JSON.parse(res.data).data;
            else if (type == 2)
              _.vehicleInfo.vehicleLicenseReversePic = JSON.parse(res.data).data;
            else if (type == 3)
              _.vehicleInfo.operationLicensePic = JSON.parse(res.data).data;
          },
          fail(err) { }
        });
      },
      // 移出图片函数
      async deletephotoFace() {
        let that = this;
        that.imagesPathFace = [];
        that.imagesPathFace.push({
          url: config.baseImgUrl + '/id-face.png',
          extname: '',
          name: ''
        });
      },
      // 移出图片函数
      async deletephotoBack() {
        let that = this;
        that.imagesPathBack = [];
        that.imagesPathBack.push({
          url: config.baseImgUrl + '/id-back.png',
          extname: '',
          name: ''
        });
      },
      limitLength(event, minLength, maxLength) {
        const inputLength = event.target.value.length;
        if (inputLength > maxLength) {
          uni.showToast({
            title: `车牌号长度${minLength}到${maxLength}位`
          });
        } else if (inputLength < minLength) {
          uni.showToast({
            title: `车牌号长度${minLength}到${maxLength}位`
          });
        }
      },
      handleVehicleNo() {
        this.vehicleInfo.vehicleNo = this.vehicleInfo.vehicleNo ? (this.vehicleInfo.vehicleNo).toUpperCase().replace(/ /g, '') : ''
      }
    }
  };
</script>

<style lang="scss" scoped>
  .content {
    .qrsf {
      .title {
        margin-bottom: 20 rpx;
        word-spacing: 10 rpx;
        letter-spacing: 1 rpx;
        width: 190 rpx;
      }

      .sjxj {
        margin-bottom: 80px;
        padding: 20 rpx 20 rpx;

        .uni-form-item {
          margin-bottom: 20 rpx;
          display: flex;
          justify-content: space-between;

          .title {
            width: 230rpx;
          }

          .title.wd220 {
            width: 220 rpx;
            text-align: right;
          }

          .uni-input {
            flex: 3;
            border: 1px solid #e5e5e5;
            height: 61 rpx;
            border-radius: 10 rpx;
            padding: 0 10 rpx;
            background-color: #fff;
            margin-left: 16 rpx;
          }
        }
      }
    }

    .uni-form-item {
      .title {
        width: 25%;
        text-align: left;
      }

      .val {
        width: 75%;
      }

      .uni-input {
        flex: 3;
        padding: 0 10 rpx;
      }

      .uni-input.vehicleno {
        border: 1px solid #e5e5e5;
        height: 35px;
        border-radius: 3px;
      }

      .uni-input.prd-mess {
        border-bottom: 1px solid #ccc;
        border-radius: 0;
        height: 40px;
        text-align: right;
      }

      .cover-img {
        border: 1 rpx #ccc solid;
      }

      .cover-img,
      .cover-defaultImg {
        width: 100 rpx;
        height: 100 rpx;
        display: inline-block;
        margin-left: 0 rpx;
        border-radius: 10px;
      }

      .img-box {
        flex: 3;
      }

      .cover-defaultImg {
        margin-left: 10 rpx;
      }
    }
  }
</style>